package chapter14_构建自定义的同步工具.显示条件变量的有界缓存;

import annotation.GuardedBy;
import annotation.ThreadSafe;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@ThreadSafe
public class ConditionBoundedBuffer<T> {
    protected final Lock lock = new ReentrantLock();
    // 条件谓词:notFull (count < items.length)
    private final Condition notFull = lock.newCondition();
    // 条件谓词:notEmpty (count>0)
    private final Condition notEmpty = lock.newCondition();
    @GuardedBy("lock")
    private final T[] items = (T[]) new Object[1024];
    @GuardedBy("lock")
    private int tail, head, count;

    // 阻塞并知道:notFull
    public void put(T x) throws InterruptedException {
        lock.lock();
        try {
            while (count == items.length) {
                //非满等待
                notFull.await();
            }
            items[tail] = x;
            if (++tail == items.length) {
                tail = 0;
            }
            ++count;
            // 唤醒非空等待线程
            notEmpty.signal();
        } finally {
            lock.unlock();
        }
    }

    public T take() throws InterruptedException {
        lock.lock();
        try {
            while (count == 0) {
                notEmpty.await();
            }
            T x = items[head];
            if (++head == items.length) {
                head = 0;
            }
            --count;
            //唤醒非满等待的线程
            notFull.signal();
            return x;
        } finally {
            lock.unlock();
        }
    }
}
